package com.wfcm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wfcm.entity.WfCollageActivityEntity;
import com.wfcm.utils.ConstantUtil;
import com.wfcm.wxPay.WXPay;
import com.wfcm.wxPay.WXPrepay;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.wfcm.dao.WfCollageOrderDao;
import com.wfcm.entity.WfCollageOrderEntity;
import com.wfcm.service.WfCollageOrderService;

import javax.servlet.http.HttpServletRequest;


@Service("wfCollageOrderService")
public class WfCollageOrderServiceImpl implements WfCollageOrderService {
    private Logger log = Logger.getLogger(Properties.class);

    @Autowired
    private WfCollageOrderDao wfCollageOrderDao;

    @Override
    public WfCollageOrderEntity queryObject(Integer id) {
        return wfCollageOrderDao.queryObject(id);
    }

    @Override
    public WfCollageOrderEntity queryMyCollage(Map<String, Object> map) {
        return wfCollageOrderDao.queryMyCollage(map);
    }

    @Override
    public WfCollageOrderEntity queryCollaging(Map<String, Object> map) {
        return wfCollageOrderDao.queryCollaging(map);
    }

    @Override
    public WfCollageOrderEntity queryLeaderCollage(Map<String, Object> map) {
        return wfCollageOrderDao.queryLeaderCollage(map);
    }

    //获取团长正在拼团中的信息
    @Override
    public WfCollageOrderEntity queryLeaderCollaging(Map<String, Object> map) {
        return wfCollageOrderDao.queryLeaderCollaging(map);
    }

    @Override
    public List<WfCollageOrderEntity> queryIsCollage(Map<String, Object> map) {
        return wfCollageOrderDao.queryIsCollage(map);
    }

    @Override
    public List<WfCollageOrderEntity> queryPartners(Map<String, Object> map) {
        return wfCollageOrderDao.queryPartners(map);
    }

    @Override
    public List<WfCollageOrderEntity> queryNotSuccess(Map<String, Object> map) {
        return wfCollageOrderDao.queryNotSuccess(map);
    }

    @Override
    public List<WfCollageOrderEntity> queryList(Map<String, Object> map) {
        return wfCollageOrderDao.queryList(map);
    }

    @Override
    public List<WfCollageOrderEntity> queryRandomList(Map<String, Object> map) {
        return wfCollageOrderDao.queryRandomList(map);
    }

    @Override
    public List<WfCollageOrderEntity> queryRandomLeader(Map<String, Object> map) {
        return wfCollageOrderDao.queryRandomLeader(map);
    }

    @Override
    public List<WfCollageOrderEntity> queryListByToUserId(String toUserId) {
        return wfCollageOrderDao.queryListByToUserId(toUserId);
    }

    @Override
    public List<WfCollageOrderEntity> queryListByUserId(String userId) {
        return wfCollageOrderDao.queryListByUserId(userId);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return wfCollageOrderDao.queryTotal(map);
    }

    @Override
    public int queryRandomTotal(Map<String, Object> map) {
        return wfCollageOrderDao.queryRandomTotal(map);
    }

    @Override
    public void save(WfCollageOrderEntity wfCollageOrder) {
        wfCollageOrderDao.save(wfCollageOrder);
    }

    @Override
    public void update(WfCollageOrderEntity wfCollageOrder) {
        wfCollageOrderDao.update(wfCollageOrder);
    }

    @Override
    public void delete(Integer id) {
        wfCollageOrderDao.delete(id);
    }

    @Override
    public void deleteBatch(Integer[] ids) {
        wfCollageOrderDao.deleteBatch(ids);
    }

    @Override
    public List<WfCollageOrderEntity> queryByOrderCode(String orderCode) {
        return wfCollageOrderDao.queryByOrderCode(orderCode);
    }

    @Override
    public JSONObject dopay(HttpServletRequest request, String orderNum, BigDecimal actualPrice,
                            Integer orderType, String openid) throws Exception {
        JSONObject res = new JSONObject();
        res.put("errCode", 0);
        //通知的URL
        //String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()  + request.getContextPath() + "/";
        String basePath = "";
        if("product".equals(ConstantUtil.environment)){
            basePath = "http://wfnx.wfkids.net/wfcm-api/";
        }else{
            basePath = "https://wftest.wfkids.net/wfcm-api/";
        }
        String notifyUrl = basePath + "pin/wechatreceive";
        System.out.println(notifyUrl);
        String prepayid = getGgWXPrePayId(request, orderNum, actualPrice, orderType, notifyUrl, openid);
        if (prepayid != null && prepayid.length() > 10) {
            // 生成微信支付参数，此处拼接为完整的JSON格式，符合支付调起传入格式
            String jsParam = WXPay.createPublicPackageValue(ConstantUtil.GG_APP_ID, ConstantUtil.GG_PARTNER_KEY, prepayid);
            log.info("生成的微信调起参数为：" + jsParam);
            // 此处可以添加订单的处理逻辑
            JSONObject params = JSONObject.parseObject(jsParam);
            res.putAll(params);
        }
        return res;
    }

    @Override
    public JSONObject doAppPay(HttpServletRequest request, String orderNum, BigDecimal actualPrice, Integer orderType) throws Exception {
        JSONObject res = new JSONObject();
        res.put("errCode", 0);
        //通知的URL
        //String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()  + request.getContextPath() + "/";
        String basePath = "";
        if("product".equals(ConstantUtil.environment)){
            basePath = "http://wfnx.wfkids.net/wfcm-api/";
        }else{
            basePath = "https://wftest.wfkids.net/wfcm-api/";
        }
        String notifyUrl = basePath + "pin/appwechatreceive";
        System.out.println(notifyUrl);
        String prepayid = getWXPrePayId(request, orderNum, actualPrice, orderType, notifyUrl);
        if (prepayid != null && prepayid.length() > 10) {
            // 生成微信支付参数，此处拼接为完整的JSON格式，符合支付调起传入格式
            String jsParam = WXPay.createPackageValue(ConstantUtil.APP_ID, ConstantUtil.PARTNER_KEY, prepayid);
            log.info("生成的微信调起参数为：" + jsParam);
            // 此处可以添加订单的处理逻辑
            JSONObject params = JSONObject.parseObject(jsParam);
            res.putAll(params);
        }
        return res;
    }

    /**
     * 创建微信prepayid
     *
     * @param notifyUrl
     * @return
     */
    private String getWXPrePayId(HttpServletRequest request, String orderCode, BigDecimal actualPrice,
                                 Integer orderType, String notifyUrl) {
        String payMoney = String.valueOf(actualPrice.multiply(new BigDecimal(100)).intValue());
        String item ="王芳课堂-APP";
        if("test".equals(ConstantUtil.environment)){// 写死0.01元
            payMoney = "1";//单位为分
        }
        String remoteIPAddress = request.getRemoteAddr();
        //remoteIPAddress="123.57.80.58";
        // 商户相关资料
        String appid = ConstantUtil.APP_ID;
        // String appsecret = ConstantUtil.APP_SECRET;
        String partner = ConstantUtil.PARTNER;
        String partnerkey = ConstantUtil.PARTNER_KEY;

        WXPrepay prePay = new WXPrepay();
        prePay.setAppid(appid);
        prePay.setBody(item);
        prePay.setPartnerKey(partnerkey);
        prePay.setMch_id(partner);
        prePay.setNotify_url(notifyUrl);
        prePay.setOut_trade_no(orderCode);
        prePay.setSpbill_create_ip(remoteIPAddress);
        prePay.setTotal_fee(payMoney);
        prePay.setTrade_type("APP");

        String prepayid = prePay.submitXmlGetPrepayId();
        log.info("获取的预支付订单是：" + prepayid);
        return prepayid;
    }

    /**
     * 创建微信prepayid
     *
     * @param notifyUrl
     * @return
     */
    @SuppressWarnings("unused")
    private String getGgWXPrePayId(HttpServletRequest request, String orderCode, BigDecimal actualPrice,
                                   Integer orderType, String notifyUrl, String openid) {
        String payMoney = String.valueOf(actualPrice.multiply(new BigDecimal(100)).intValue());
        String item = "王芳课堂-拼团活动";
        if("test".equals(ConstantUtil.environment)){// 写死0.01元
            payMoney = "1";//单位为分
        }
        String remoteIPAddress = request.getRemoteAddr();
        //remoteIPAddress="123.57.80.58";
        // 商户相关资料
        String appid = ConstantUtil.GG_APP_ID;
        //String appsecret = ConstantUtil.APP_SECRET;
        String partner = ConstantUtil.GG_PARTNER;
        String partnerkey = ConstantUtil.GG_PARTNER_KEY;

        WXPrepay prePay = new WXPrepay();
        prePay.setAppid(appid);
        prePay.setBody(item);
        prePay.setPartnerKey(partnerkey);
        prePay.setMch_id(partner);
        prePay.setNotify_url(notifyUrl);
        prePay.setOut_trade_no(orderCode);
        prePay.setSpbill_create_ip(remoteIPAddress);
        prePay.setTotal_fee(payMoney);
        prePay.setTrade_type("JSAPI");
        prePay.setOpenid(openid);

        String prepayid = prePay.submitGgXmlGetPrepayId();
        log.info("获取的预支付订单是：" + prepayid);
        return prepayid;
    }

    @Override
    public WfCollageOrderEntity queryGroupBuying(Integer toUserId, Integer activityId, Integer status) {
        return wfCollageOrderDao.queryGroupBuying(toUserId, activityId, status);
    }

    @Override
    public List<WfCollageOrderEntity> queryGroupBuyList(String collageOrder) {
        return wfCollageOrderDao.queryGroupBuyList(collageOrder);
    }

    @Override
    public List<WfCollageOrderEntity> record(Integer userId, Integer start, Integer end) {
        return wfCollageOrderDao.record(userId, start, end);
    }

    @Override
    public Integer recordTotal(Integer userId) {
        return wfCollageOrderDao.recordTotal(userId);
    }

    @Override
    public List<String> queryHeadImgs(Integer activityId) {
        return wfCollageOrderDao.queryHeadImgs(activityId);
    }

    @Override
    public List<WfCollageOrderEntity> queryRandomGroupBuyList(Integer activityId, Integer start, Integer end) {
        List<WfCollageOrderEntity> collageOrderEntityList = wfCollageOrderDao.queryRandomGroupBuyList(activityId, start, end);
        for (int i = 0; i < collageOrderEntityList.size(); i++) {
            if(null == collageOrderEntityList.get(i).getWxHeadImage()){
                collageOrderEntityList.get(i).setWxHeadImage(getRandomHead());
            }
        }
        return collageOrderEntityList;
    }

    @Override
    public Integer queryRandomGroupBuyTotal(Integer activityId) {
        return wfCollageOrderDao.queryRandomGroupBuyTotal(activityId);
    }

    String getRandomHead(){
        java.util.Random random=new java.util.Random();// 定义随机类
        int result=random.nextInt(6);// 返回[0,10)集合中的整数，注意不包括10
        String[] strArray={"random_head/01.png","random_head/02.png","random_head/03.png","random_head/04.png","random_head/05.png","random_head/06.png"};
        return strArray[result];              // +1后，[0,10)集合变为[1,11)集合，满足要求
    }

}
